package com.larry.rabbitmq.eighth;

import com.larry.rabbitmq.util.RabbitMQUtils;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Delivery;

import java.util.HashMap;
import java.util.Map;

/**
 * @author larry
 * @Title: larry-rabbitmq
 * @Package com.larry.rabbitmq.eighth
 * @Description: 死信队列 消费者
 * @date 7/4/212:23 PM
 */
public class Consumer01 {

    //普通交换机名称
    public static final String NORMAL_EXCHANGE = "normal_exchange";
    //死信交换机名称
    public static final String DEAD_EXCHANGE = "dead_exchange";
    //普通队列名称
    public static final String NORMAL_QUEUE = "normal_queue";
    //死信队列名称
    public static final String DEAD_QUEUE = "dead_queue";


    public static void main(String args[]) throws Exception{
        Channel channel = RabbitMQUtils.getChannel();

        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);
        channel.exchangeDeclare(DEAD_EXCHANGE,BuiltinExchangeType.DIRECT);

        //普通队列
        Map<String, Object> arguments = new HashMap<>();
        //过期时间
//        arguments.put("x-message-ttl",10000);
        //正常队列设置死信交换机
        arguments.put("x-dead-letter-exchange",DEAD_EXCHANGE);
        //设置死信routingkey
        arguments.put("x-dead-letter-routing-key","lisi");
        //设置正常队列的长度限制
        arguments.put("x-max-length",6);
        channel.queueDeclare(NORMAL_QUEUE,false,false,false,arguments);


        //死信队列
        channel.queueDeclare(DEAD_QUEUE,false,false,false,null);

        //绑定
        channel.queueBind(NORMAL_QUEUE,NORMAL_EXCHANGE,"zhangsan");
        channel.queueBind(DEAD_QUEUE,DEAD_EXCHANGE,"lisi");


        channel.basicConsume(NORMAL_QUEUE,false,(consumerTag, message) -> {
            String msg = new String(message.getBody());
            //拒绝消息
            if (msg.equals("info5")){
                channel.basicReject(message.getEnvelope().getDeliveryTag(),false);
            }else {
                channel.basicAck(message.getEnvelope().getDeliveryTag(),false);
            }
            System.out.println("Consumer01消息: " + msg);
        },consumerTag -> {});
    }
}
